<?php

namespace app\controller;

use app\BaseController;
use app\model\Category;
use app\model\OrdersItem;
use app\utils\simple_html_dom;
use think\App;
use think\Db;
use think\db\Where;
use think\facade\Cache;
use think\facade\View;

//require 'vendor/autoload.php';
use Firebase\JWT\JWT;


class CourseController extends BaseController
{

    var $courseModel;
    var $categoryModel;
    var $menuModel;
    var $redis;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->courseModel = new \app\model\Course();
        $this->categoryModel = new \app\model\Category();
        $this->menuModel = new \app\model\Menu();
        $this->redis = Cache::store('redis');
    }


    //查询课程订单信息
    public function courseOrder($user_id, $course_id){
        $sql = "select * from order_item a left join orders b on a.order_id=b.id where b.user_id=:uid and a.course_id=:cid and b.state=1";
        $items = \think\facade\Db::query($sql,['uid' => $user_id,'cid' => $course_id]);
        if (count($items)>0){
            return $items[0];
        }
        return null;
    }

    public function index($course_id)
    {

        if (true) {
            //return redirect('/course/'.$course_id.'/task');
        }

        $cache = Cache::store('redis');
        $arr = [];
        $course = $this->courseModel->where('id', $course_id)->find();

        $tb = \think\facade\Db::table('course_introduction');
        $ci = $tb->where('course_id', $course_id)->find();

        if ($ci){
            $intro = $ci['introduction'];
        }else{
            $intro = '';
        }

        View::assign('course', $course);
        View::assign('introduction', $intro);
        View::assign('courseOrder', $this->courseOrder(1, $course_id)==null );


        //return json_encode(['code'=>0, 'msg' => '查询成功'],JSON_UNESCAPED_UNICODE);
        return view("/course/index");
    }

    public function task($course_id)
    {

        $cache = Cache::store('redis');
        $arr = [];
        $course = $this->courseModel->where('id', $course_id)->find();


        $tb = \think\facade\Db::table('lesson');
        $list = $tb->where('course_id', $course_id)->select();

        View::assign('lessons', $list);
        View::assign('course', $course);
        View::assign('courseOrder', $this->courseOrder(1, $course_id)==null );


        //return json_encode(['code'=>0, 'msg' => '查询成功'],JSON_UNESCAPED_UNICODE);
        return view("/course/task");
    }



    public function learn($lesson_id)
    {
        $isOwn = 0;

        $cache = \think\facade\Cache::store('redis');

        $tb = \think\facade\Db::table('lesson');
        $lesson = $tb->where('id', $lesson_id)->find();

        $course_id = $lesson['course_id'];
        $course = $this->courseModel->where('id', $course_id)->find();
        $isfree = ($lesson['is_free'] == 1);

        if ($lesson['is_free'] == 1) {

        }

        $loginUser = session('login_user');
        if ($loginUser) {
            $key = 'user-course:'.$loginUser['id'].'-'.$course_id; //记录是否已选课
            if (!$cache->has($key)) {
                $userCourse = \think\facade\Db::table('user_course')
                    ->where('course_id',$course_id)
                    ->where('user_id',$loginUser['id'])
                    ->find();

                if ($userCourse!=null) {
                    $cache->set($key, true,3600*24*7);
                }
            }
            $isOwn = ($cache->get($key)==true);
        }

        View::assign('is_own',$isOwn );
        View::assign('is_free',$isfree );

        $list = \think\facade\Db::table('lesson')->where('course_id',$course_id)->select();

        $video_url = $this->getVideoUrlByLessonId($lesson_id);

        View::assign('task',$lesson);
        View::assign('course',$course);
        View::assign('lesson',$lesson);
        View::assign('list',$list);
        View::assign('video_url',$video_url);

        return view("/course/video");
    }


    public function play($course_id, $lesson_id)
    {
/*
        $appId = 1252460838; // 用户 appid
        $fileId = "387702293559253378"; // 目标 FileId
        $currentTime = time();
        $psignExpire = $currentTime + 1800; // 可任意设置过期时间，示例1h
        $urlTimeExpire = dechex($psignExpire); // 可任意设置过期时间，16进制字符串形式，示例1h
        $key = "XK1RrVSvlC2jsETbBeMv";

        $payload = array(
            "appId" => $appId,
            "fileId" => $fileId,
            "currentTimeStamp" => $currentTime,
            "expireTimeStamp" => $psignExpire,
            "urlAccessInfo" => array(
                "t" => $urlTimeExpire,
                "rlimit"=> 2
            )
        );

        $jwt = JWT::encode($payload, $key, 'HS256');
        print_r($jwt);
*/
        $isOwn = 0;

        $cache = \think\facade\Cache::store('redis');

        $loginUser = session('login_user');
        if ($loginUser) {
            $key = 'user-course:'.$loginUser['id'].'-'.$course_id; //记录是否已选课
            if (!$cache->has($key)) {
                $userCourse = \think\facade\Db::table('user_course')
                    ->where('course_id',$course_id)
                    ->where('user_id',$loginUser['id'])
                    ->find();

                //print_r($userCourse);
                if ($userCourse!=null) {
                    $cache->set($key, true,3600*24*7);
                }else{
                    $cache->set($key, false,3600*24*7);
                }
            }
            $isOwn = $cache->get($key);
        }

        $course = $this->courseModel->where('id', $course_id)->find();

        $lesson = \think\facade\Db::table('lesson')
            ->where('id',$lesson_id)
            ->where('is_free',1)
            ->find();
        //print_r($lesson);
        View::assign('is_own',$isOwn );
        View::assign('is_free',$lesson!=null );

        $tb = \think\facade\Db::table('lesson');
        $lesson = $tb->where('id', $lesson_id)->find();
        $list = \think\facade\Db::table('lesson')->where('course_id',$course_id)->select();


        //$url = $lesson['video_url'];
        $video_url = $this->getVideoUrlByLessonId($lesson_id);

        View::assign('task',$lesson);
        View::assign('course',$course);
        View::assign('lesson',$lesson);
        View::assign('list',$list);
        View::assign('video_url',$video_url);

        return view("/course/play3");
    }


    //course/explore/{}
    public function explore($category_code='')
    {

        $courseModel = new \app\model\Course();

        $query = $courseModel->where('state', 3);

        if (!$category_code) {
            //默认查询全部类别
            //echo $category_code;
            //$query = $courseModel->where('state', 3);
        }else{
            //$query = $courseModel->where('category.code', $category_code);
            $query->withJoin('category')->where('category.code', $category_code);

            //查询当前类别
            $category = $this->categoryModel->where('code', $category_code)->find();
            View::assign('category', $category);
        }



        //课程排序
        $sort = $this->request->get('sort', '');
        View::assign('sort', $sort);
        switch ($sort) {
            case 'latest':
                $query->order('create_time desc');break;
            case 'hot':
                $query->order('students_amount desc');break;
            case 'nb':
                $query->order('score desc');break;
        }


        //查询全部类别
        $categoryList = $this->categoryModel->select();
        View::assign('categoryList', $categoryList);

        //课程列表
        //$courseList = $query->select();

        $page = $this->request->param('page', 1);
        $rows = 20;
        $result = $query->paginate([
            'list_rows'=>$rows,'page'=>$page
        ]);
        $total = $result->total();
        $pages =  ceil($total/$rows);
        $paging = [
            'total'=>$result->total(),                    //总记录数
            'pages'=>$pages,                            //总页数
            'curr'=>$page,                              //当前第几页
            'rows'=>$rows,                              //每页记录数
            'prev'=>$page<2?1:$page-1,                  //上一页
            'next'=>$page>$pages-1?$pages:$page+1,      //下一页
            'list'=>$result,                               //数据列表
            'sort'=>$sort                               //排序参数
        ];
        View::assign('courseList', $result);
        View::assign('paging', $paging);




        return view("/course/explore");
    }


    public function getVideoUrlByLessonId($lesson_id){
        $sql = "select *,b.type v_type from lesson a left join video b on a.video_id=b.id where a.id=:lid";
        $items = \think\facade\Db::query($sql,['lid' => $lesson_id]);
        if (count($items)>0){
            $item = $items[0];
            $url = $item['url'];
            if ($item['v_type'] == 2) {
                $url = qq_vod_sign($url);
            }
            if ($item['v_type'] == 3) {
                $url = qn_sign($url);
            }
            return $url;
        }
    }


    //加入学习
    public function buy($course_id)
    {
        echo 'buy';
        /*$cache = Cache::store('redis');
        $arr = [];
        $course = $this->courseModel->where('id', $course_id)->find();
        View::assign('course', $course);

        $topMenuList = $this->menuModel->where('pid', '0')->select();
        View::assign('topMenuList', $topMenuList);

        //return json_encode(['code'=>0, 'msg' => '查询成功'],JSON_UNESCAPED_UNICODE);
        return view("/course/intro");*/
/*
        $user = session('login_user');
        if ($user == null) {
            return json_encode(['code'=>600, 'msg' => '未登录'],JSON_UNESCAPED_UNICODE);
        }

*/
        // 先查询是否买过此课
        $ordersItemModel = new \app\model\OrdersItem();
        $ordersModel = new \app\model\Orders();
        $order = $this->courseOrder(1, $course_id);
        if ($order != null){
            return json_encode(['code'=>1, 'msg' => '已拥有此课程'],JSON_UNESCAPED_UNICODE);
        }

        //生成订单
        $ordersModel->insert([
            'order_sn'=>build_order_no(),
            'user_id'=>1,
            'state'=>0,

        ]);

}

    function build_order_no()
    {
        /* 选择一个随机的方案 */
        //mt_srand((double) microtime() * 1000000);
        /* PHPALLY + 年月日 + 6位随机数 */
        return date('YmdHis') . str_pad(mt_rand(1, 999999), 6, '0', STR_PAD_LEFT);
    }

    function msectime() {
        list($msec, $sec) = explode(' ', microtime());
        $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        return $msectime;
    }

}